<template>
    <div style="padding: 20px;">
        <h3 style="padding: 0 0 10px 0;margin: 0;">图片处理</h3>
        <!-- 上传图片 -->
        <el-upload ref="uploadRef" class="upload-demo" :auto-upload="false" :limit="1" :on-exceed="handleExceed"
            :on-change="onImageUpload2">

            <template #trigger>
                <el-button type="primary">上传</el-button>
            </template>

            <el-button class=" ml-3" type="success" @click="submitImage">
                保存
            </el-button>

            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500kb
                </div>
            </template>
        </el-upload>

        <!-- Canvas 显示区域 -->
        <div class="canvas-container">
            <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight" />
        </div>
        <br />

        <!-- 文字输入框 -->
        <label for="text-input">输入文字：</label>
        <input type="text" v-model="text" id="text-input" placeholder="输入文字" @input="drawText" />
        <br />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { genFileId } from 'element-plus'

// 图片、文字和位置数据
const image = ref(null);
const text = ref('');
const textX = ref(50);
const textY = ref(50);
const fontSize = ref(36);

// Canvas 设置
const canvasWidth = 500;
const canvasHeight = 500;
const canvas = ref(null);
const ctx = ref(null);

// 鼠标拖动控制的状态
const isDragging = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);

const uploadRef = ref()

const fuckImageUrl = ref("")

//覆盖图片
const handleExceed = (files) => {
    // 清空已上传的文件
    uploadRef.value.clearFiles();
    // 取出第一个文件
    const file = files[0];
    // 为文件生成一个唯一的 ID（假设你有一个 genFileId 函数来生成 ID）
    file.uid = genFileId();
    // 开始上传文件
    uploadRef.value.handleStart(file);
};

// 上传图片并显示在 Canvas 上
const onImageUpload2 = (fileList) => {
    // 获取上传的文件（fileList是一个数组，获取第一个文件）
    const file = fileList.raw;
    const imgUrl = URL.createObjectURL(file);
    fuckImageUrl.value = imgUrl;

    // 创建一个 Image 对象并加载图片
    const img = new Image();
    img.onload = () => {
        image.value = img; // 将图片对象保存在 image 引用中
        drawImage(); // 调用 drawImage 将图片绘制到 canvas 上
    };
    img.src = imgUrl; // 设置图片源为刚生成的 URL
};

// 在 Canvas 上绘制图片
const drawImage = () => {
    if (canvas.value && image.value) {
        ctx.value = canvas.value.getContext('2d');
        ctx.value.clearRect(0, 0, canvasWidth, canvasHeight);
        ctx.value.drawImage(image.value, 0, 0, canvasWidth, canvasHeight);
        drawText();
    }
};

// 绘制文字到 Canvas
const drawText = () => {
    if (ctx.value) {
        ctx.value.clearRect(0, 0, canvasWidth, canvasHeight); // 清除之前的画布
        ctx.value.drawImage(image.value, 0, 0, canvasWidth, canvasHeight); // 重新绘制图片
        ctx.value.font = `${fontSize.value}px Arial`;
        ctx.value.fillStyle = 'red'; // 文字颜色
        ctx.value.fillText(text.value, textX.value, textY.value);
    }
};

// 鼠标按下时开始拖动
const onMouseDown = (e) => {
    const mouseX = e.offsetX;
    const mouseY = e.offsetY;

    // 检查点击是否在文字范围内
    if (
        mouseX > textX.value &&
        mouseX < textX.value + ctx.value.measureText(text.value).width &&
        mouseY > textY.value - fontSize.value &&
        mouseY < textY.value
    ) {
        isDragging.value = true;
        dragStartX.value = mouseX - textX.value;
        dragStartY.value = mouseY - textY.value;
    }
};

// 鼠标移动时更新文字位置
const onMouseMove = (e) => {
    if (isDragging.value) {
        const mouseX = e.offsetX;
        const mouseY = e.offsetY;

        // 更新文字位置
        textX.value = mouseX - dragStartX.value;
        textY.value = mouseY - dragStartY.value;

        // 重新绘制画布
        drawImage();
    }
};

// 鼠标释放时停止拖动
const onMouseUp = () => {
    isDragging.value = false;
};

// 提交图片到后端
const submitImage = async () => {
    const imgData = canvas.value.toDataURL('image/png');
    const data = {
        text: text.value,
        x: textX.value,
        y: textY.value,
        fontSize: fontSize.value,
        image: imgData,
    };

    // 将数据发送到后端
    const response = await fetch('/upload_image', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    });

    const result = await response.json();
    console.log('上传结果:', result);
};

// 确保 Canvas 已挂载到 DOM 后绑定事件
onMounted(() => {
    const canvasElement = canvas.value;
    if (canvasElement) {
        canvasElement.addEventListener('mousedown', onMouseDown);
        canvasElement.addEventListener('mousemove', onMouseMove);
        canvasElement.addEventListener('mouseup', onMouseUp);
    }
});
</script>

<style scoped>
.canvas-container {
    position: relative;
    display: inline-block;
    border: 1px solid #ccc;
}

canvas {
    display: block;
}
</style>